<template>
  <div class="login">
    <div class="form-wrapper">
      <el-form
        ref="formRef"
        :model="form"
        :style="{ width: '350px' }"
        status-icon
        label-width="0px"
      >
        <el-form-item prop="username">
          <el-input v-model="form.username" type="text" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item v-show="showSlider">
          <div id="loginSlider" class="nc-container"></div>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleSubmit(formRef)">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import type { FormInstance } from 'element-plus';
import config from '@/config';
import { login } from '@/api/auth';
import { appLoginHandler } from '@appGateway';

defineOptions({
  name: 'AccountIndex'
});

const form = reactive({
  username: '',
  password: ''
});

const formRef = ref<FormInstance>();

const showSlider = ref<boolean>(false);

const handleSubmit = ({ errors }: any) => {
  if (errors) {
    return;
  }

  InitLoginSlider();
};

function InitLoginSlider() {
  showSlider.value = true;
  const ncToken = [config.captchaKey, new Date().getTime(), Math.random()].join(':');
  const NC_OPT = {
    renderTo: '#loginSlider',
    appkey: config.captchaKey,
    scene: 'nc_login',
    token: ncToken,
    customWidth: 288,
    trans: { key1: 'code0' },
    elementID: ['usernameID'],
    // eslint-disable-next-line camelcase
    is_Opt: 0,
    language: 'cn',
    isEnabled: true,
    timeout: 3000,
    times: 5,
    apimap: {},
    callback: async function (result: any) {
      const params = {
        userName: form.username,
        password: form.password,
        sessionId: result.csessionid,
        token: ncToken,
        sig: result.sig
      };
      const { err, data } = await login(params);
      if (err) return;

      const token = data?.accessToken;
      // const expires = data?.expiresIn;
      // const authStore = useAuthStore();
      // auth.setToken(token as string, expires);
      appLoginHandler(token);
    }
  };
  const nc = new noCaptcha(NC_OPT);
  nc.upLang('cn', {
    _startTEXT: '请按住滑块，拖动到最右边',
    _yesTEXT: '验证通过',
    _error300: '哎呀，出错了，点击<a href="javascript:__nc.reset()">刷新</a>再来一次',
    _errorNetwork: '网络不给力，请<a href="javascript:__nc.reset()">点击刷新</a>'
  });
}
</script>

<style lang="scss" scoped>
.login {
  height: 100%;

  .form-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }
}
</style>
